home *** CD-ROM | disk | FTP | other *** search
/ Chip 2002 July / 07_02.iso / macos / files / Netscape-mac-full.bin / Netscape-mac-full / Netscape Full Installer / Installer Modules / browser.xpi / viewer / Components / nsUpdateNotifier.js < prev    next >
Text File  |  2002-05-12  |  17KB  |  474 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is the Update Notifier.
  15.  *
  16.  * The Initial Developer of the Original Code is 
  17.  * Netscape Communications Corporation.
  18.  * Portions created by the Initial Developer are Copyright (C) 2002
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *  Samir Gehani <sgehani@netscape.com> (Original Author) 
  23.  *
  24.  * Alternatively, the contents of this file may be used under the terms of
  25.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  26.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27.  * in which case the provisions of the GPL or the LGPL are applicable instead
  28.  * of those above. If you wish to allow use of your version of this file only
  29.  * under the terms of either the GPL or the LGPL, and not to allow others to
  30.  * use your version of this file under the terms of the MPL, indicate your
  31.  * decision by deleting the provisions above and replace them with the notice
  32.  * and other provisions required by the GPL or the LGPL. If you do not delete
  33.  * the provisions above, a recipient may use your version of this file under
  34.  * the terms of any one of the MPL, the GPL or the LGPL.
  35.  *
  36.  * ***** END LICENSE BLOCK ***** */
  37.  
  38. const kDebug               = false;
  39. const kUpdateCheckDelay    = 5 * 60 * 1000; // 5 minutes
  40. const kUNEnabledPref       = "update_notifications.enabled";
  41. const kUNDatasourceURIPref = "update_notifications.provider.0.datasource";
  42. const kUNFrequencyPref     = "update_notifications.provider.0.frequency";
  43. const kUNLastCheckedPref   = "update_notifications.provider.0.last_checked";
  44. const kUNBundleURI         = 
  45.   "chrome://communicator/locale/update-notifications.properties";
  46.  
  47. ////////////////////////////////////////////////////////////////////////
  48. // 
  49. //   nsUpdateNotifier : nsIProfileStartupListener, nsIObserver
  50. //
  51. //   Checks for updates of the client by polling a distributor's website
  52. //   for the latest available version of the software and comparing it
  53. //   with the version of the running client.
  54. //
  55. ////////////////////////////////////////////////////////////////////////
  56.  
  57. var nsUpdateNotifier = 
  58. {
  59.   onProfileStartup: function(aProfileName)
  60.   {
  61.     debug("onProfileStartup");
  62.  
  63.     // now wait for the first app window to open
  64.     var observerService = Components.
  65.       classes["@mozilla.org/observer-service;1"].
  66.       getService(Components.interfaces.nsIObserverService);
  67.     observerService.addObserver(this, "domwindowopened", false);
  68.   },
  69.  
  70.   mTimer: null, // need to hold on to timer ref
  71.  
  72.   observe: function(aSubject, aTopic, aData)
  73.   {
  74.     debug("observe: " + aTopic);
  75.  
  76.     if (aTopic == "domwindowopened")
  77.     {
  78.       try 
  79.       {
  80.         const kIScriptableTimer = Components.interfaces.nsIScriptableTimer;
  81.         mTimer = Components.classes["@mozilla.org/timer;1"].
  82.           createInstance(kIScriptableTimer);
  83.         mTimer.init(this, kUpdateCheckDelay, kIScriptableTimer.PRIORITY_NORMAL,
  84.           kIScriptableTimer.TYPE_ONE_SHOT);
  85.  
  86.         // we are no longer interested in the ``domwindowopened'' topic
  87.         var observerService = Components.
  88.           classes["@mozilla.org/observer-service;1"].
  89.           getService(Components.interfaces.nsIObserverService);
  90.         observerService.removeObserver(this, "domwindowopened");
  91.       }
  92.       catch (ex)
  93.       {
  94.         debug("Exception init'ing timer: " + ex);
  95.       }
  96.     }
  97.     else if (aTopic == "timer-callback")
  98.     {
  99.       mTimer = null; // free up timer so it can be gc'ed
  100.       this.checkForUpdate();
  101.     }
  102.   },
  103.  
  104.   checkForUpdate: function()
  105.   {
  106.     debug("checkForUpdate");
  107.     
  108.     if (this.shouldCheckForUpdate())
  109.     {
  110.       try
  111.       {
  112.         // get update ds URI from prefs
  113.         var prefs = Components.classes["@mozilla.org/preferences-service;1"].
  114.           getService(Components.interfaces.nsIPrefBranch);
  115.         var updateDatasourceURI = prefs.
  116.           getComplexValue(kUNDatasourceURIPref,
  117.           Components.interfaces.nsIPrefLocalizedString).data;
  118.  
  119.         var rdf = Components.classes["@mozilla.org/rdf/rdf-service;1"].
  120.           getService(Components.interfaces.nsIRDFService);
  121.         var ds = rdf.GetDataSource(updateDatasourceURI);
  122.         
  123.         ds = ds.QueryInterface(Components.interfaces.nsIRDFXMLSink);
  124.         ds.addXMLSinkObserver(nsUpdateDatasourceObserver);
  125.       }
  126.       catch (ex)
  127.       {
  128.         debug("Exception getting updates.rdf: " + ex);
  129.       }
  130.     }
  131.   },
  132.  
  133.   shouldCheckForUpdate: function()
  134.   {
  135.     debug("shouldCheckForUpdate");
  136.  
  137.     var shouldCheck = false;
  138.  
  139.     try
  140.     {
  141.       var prefs = Components.classes["@mozilla.org/preferences-service;1"].
  142.         getService(Components.interfaces.nsIPrefBranch);
  143.   
  144.       if (prefs.getBoolPref(kUNEnabledPref))
  145.       {
  146.         var freq = prefs.getIntPref(kUNFrequencyPref) * (24 * 60 * 60); // secs
  147.         var now = (new Date().valueOf())/1000; // secs
  148.  
  149.         if (!prefs.prefHasUserValue(kUNLastCheckedPref))
  150.         {
  151.           // setting last_checked pref first time so must randomize in 
  152.           // order that servers don't get flooded with updates.rdf checks
  153.           // (and eventually downloads of new clients) all at the same time
  154.  
  155.           var randomizedLastChecked = now + freq * (1 + Math.random());
  156.           prefs.setIntPref(kUNLastCheckedPref, randomizedLastChecked);
  157.  
  158.           return false;
  159.         }
  160.  
  161.         var lastChecked = prefs.getIntPref(kUNLastCheckedPref);
  162.         if ((lastChecked + freq) > now)
  163.           return false;
  164.         
  165.         prefs.setIntPref(kUNLastCheckedPref, now);
  166.         prefs = prefs.QueryInterface(Components.interfaces.nsIPrefService);
  167.         prefs.savePrefFile(null); // flush prefs now
  168.  
  169.         shouldCheck = true;
  170.       }
  171.     }
  172.     catch (ex)
  173.     {
  174.       shouldCheck = false;
  175.       debug("Exception in shouldCheckForUpdate: " + ex);
  176.     }
  177.  
  178.     return shouldCheck;
  179.   },
  180.  
  181.   QueryInterface: function(aIID)
  182.   {
  183.     if (!aIID.equals(Components.interfaces.nsIObserver) &&
  184.         !aIID.equals(Components.interfaces.nsIProfileStartupListener) &&
  185.         !aIID.equals(Components.interfaces.nsISupports))
  186.       throw Components.results.NS_ERROR_NO_INTERFACE;
  187.  
  188.     return this;
  189.   }
  190. }
  191.  
  192. ////////////////////////////////////////////////////////////////////////
  193. //
  194. //   nsUpdateDatasourceObserver : nsIRDFXMLSinkObserver
  195. //
  196. //   Gets relevant info on latest available update after the updates.rdf
  197. //   datasource has completed loading asynchronously.
  198. //
  199. ////////////////////////////////////////////////////////////////////////
  200.  
  201. var nsUpdateDatasourceObserver = 
  202. {
  203.   onBeginLoad: function(aSink)
  204.   {
  205.   },
  206.  
  207.   onInterrupt: function(aSink)
  208.   {
  209.   },
  210.  
  211.   onResume: function(aSink)
  212.   {
  213.   },
  214.  
  215.   onEndLoad: function(aSink)
  216.   {
  217.     debug("onEndLoad");
  218.     
  219.     aSink.removeXMLSinkObserver(this);
  220.  
  221.     var ds = aSink.QueryInterface(Components.interfaces.nsIRDFDataSource);
  222.     var updateInfo = this.getUpdateInfo(ds);
  223.     if (updateInfo && this.newerVersionAvailable(updateInfo))
  224.     {
  225.       var promptService = Components.
  226.         classes["@mozilla.org/embedcomp/prompt-service;1"].
  227.         getService(Components.interfaces.nsIPromptService);
  228.       var winWatcher = Components.
  229.         classes["@mozilla.org/embedcomp/window-watcher;1"].
  230.         getService(Components.interfaces.nsIWindowWatcher);
  231.       
  232.       var unBundle = this.getBundle(kUNBundleURI);
  233.       if (!unBundle)
  234.         return;
  235.  
  236.       var title = unBundle.formatStringFromName("title", 
  237.         [updateInfo.productName], 1);
  238.       var desc = unBundle.formatStringFromName("desc", 
  239.         [updateInfo.productName], 1);
  240.       var button0Text = unBundle.GetStringFromName("getItNow");
  241.       var button1Text = unBundle.GetStringFromName("noThanks");
  242.       var checkMsg = unBundle.GetStringFromName("dontAskAgain");
  243.       var checkVal = {value:0};
  244.  
  245.       var result = promptService.confirmEx(winWatcher.activeWindow, title, desc, 
  246.         (promptService.BUTTON_POS_0 * promptService.BUTTON_TITLE_IS_STRING) +
  247.         (promptService.BUTTON_POS_1 * promptService.BUTTON_TITLE_IS_STRING),
  248.         button0Text, button1Text, null, checkMsg, checkVal);
  249.  
  250.       // user wants update now so open new window 
  251.       // (result => 0 is button0)
  252.       if (result == 0)
  253.         winWatcher.openWindow(winWatcher.activeWindow, updateInfo.URL, 
  254.           "_blank", "", null);
  255.  
  256.       // if "Don't ask again" was checked disable update notifications
  257.       if (checkVal.value)
  258.       {
  259.         var prefs = Components.classes["@mozilla.org/preferences-service;1"].
  260.           getService(Components.interfaces.nsIPrefBranch);
  261.         prefs.setBoolPref(kUNEnabledPref, false);
  262.       }
  263.     }
  264.   },
  265.  
  266.   onError: function(aSink, aStatus, aErrorMsg)
  267.   {
  268.     debug("Error " + aStatus + ": " + aErrorMsg);
  269.     aSink.removeXMLSinkObserver(this);
  270.   },
  271.  
  272.   getUpdateInfo: function(aDS)
  273.   {
  274.     var info = null;
  275.  
  276.     try
  277.     {
  278.       var rdf = Components.classes["@mozilla.org/rdf/rdf-service;1"].
  279.         getService(Components.interfaces.nsIRDFService);
  280.       var src = "urn:updates:latest";
  281.  
  282.       info = new Object;
  283.       info.registryName = this.getTarget(rdf, aDS, src, "registryName");
  284.       info.version = this.getTarget(rdf, aDS, src, "version");
  285.       info.URL = this.getTarget(rdf, aDS, src, "URL");
  286.       info.productName = this.getTarget(rdf, aDS, src, "productName");
  287.     }
  288.     catch (ex)
  289.     {
  290.       info = null;
  291.       debug("Exception getting update info: " + ex);
  292.  
  293.       // NOTE: If the (possibly remote) datasource doesn't exist 
  294.       //       or fails to load the first |GetTarget()| call will fail
  295.       //       bringing us to this exception handler.  In turn, we 
  296.       //       will fail silently.  Testing has revealed that for a 
  297.       //       non-existent datasource (invalid URI) the 
  298.       //       |nsIRDFXMLSinkObserver.onEndLoad()| is called instead of
  299.       //       |nsIRDFXMLSinkObserver.onError()| as one may expect.  In 
  300.       //       addition, if we QI the aSink parameter of |onEndLoad()| 
  301.       //       to an |nsIRDFRemoteDataSource| and check the |loaded| 
  302.       //       boolean, it reflects true so we can't use that.  The 
  303.       //       safe way to know we have failed to load the datasource 
  304.       //       is by handling the first exception as we are doing now.
  305.     }
  306.  
  307.     return info;
  308.   },
  309.  
  310.   getTarget: function(aRDF, aDS, aSrc, aProp)
  311.   {
  312.     var src = aRDF.GetResource(aSrc);
  313.     var arc = aRDF.GetResource("http://home.netscape.com/NC-rdf#" + aProp);
  314.     var target = aDS.GetTarget(src, arc, true);
  315.     return target.QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  316.   },
  317.  
  318.   newerVersionAvailable: function(aUpdateInfo)
  319.   {
  320.     // sanity check 
  321.     if (!aUpdateInfo.registryName || !aUpdateInfo.version)
  322.     {
  323.       debug("Sanity check failed: aUpdateInfo is invalid!");
  324.       return false;
  325.     }
  326.  
  327.     // XXX Once InstallTrigger is a component we will be able to
  328.     //     get at it without needing to reference it from hiddenDOMWindow.
  329.     //     This will enable us to |compareVersion()|s even when 
  330.     //     XPInstall is disabled but update notifications are enabled.
  331.     //     See <http://bugzilla.mozilla.org/show_bug.cgi?id=121506>.
  332.     //
  333.     //     Also, once |compareVersion()| is changed to return -5 when
  334.     //     the component was not registered/was removed we should change
  335.     //     this code to handle the situation and inform users that an
  336.     //     update is available.
  337.     //     See <http://bugzilla.mozilla.org/show_bug.cgi?id=119370>.
  338.     var ass = Components.classes["@mozilla.org/appshell/appShellService;1"].
  339.       getService(Components.interfaces.nsIAppShellService);
  340.     var diffLevel = ass.hiddenDOMWindow.InstallTrigger.compareVersion(
  341.                       aUpdateInfo.registryName, aUpdateInfo.version);
  342.     return (diffLevel < 0);
  343.   },
  344.  
  345.   getBundle: function(aURI)
  346.   {
  347.     if (!aURI)
  348.       return null;
  349.  
  350.     var bundle = null;
  351.     try
  352.     {
  353.       var strBundleService = Components.
  354.         classes["@mozilla.org/intl/stringbundle;1"].
  355.         getService(Components.interfaces.nsIStringBundleService);
  356.       bundle = strBundleService.createBundle(aURI);
  357.     }
  358.     catch (ex)
  359.     {
  360.       bundle = null;
  361.       debug("Exception getting bundle " + aURI + ": " + ex);
  362.     }
  363.  
  364.     return bundle;
  365.   }
  366. }
  367.  
  368. ////////////////////////////////////////////////////////////////////////
  369. //
  370. //   nsUpdateNotifierModule : nsIModule
  371. //
  372. ////////////////////////////////////////////////////////////////////////
  373.  
  374. var nsUpdateNotifierModule = 
  375. {
  376.   mClassName:     "Update Notifier",
  377.   mContractID:    "@mozilla.org/update-notifier;1",
  378.   mClassID:       Components.ID("8b6dcf5e-3b5a-4fff-bff5-65a8fa9d71b2"),
  379.  
  380.   getClassObject: function(aCompMgr, aCID, aIID)
  381.   {
  382.     if (!aCID.equals(this.mClassID))
  383.       throw Components.results.NS_ERROR_NO_INTERFACE;
  384.     if (!aIID.equals(Components.interfaces.nsIFactory))
  385.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  386.  
  387.     return this.mFactory;
  388.   },
  389.  
  390.   registerSelf: function(aCompMgr, aFileSpec, aLocation, aType)
  391.   {
  392.     if (kDebug)
  393.       dump("*** Registering nsUpdateNotifier (a JavaScript Module)\n");
  394.  
  395.     // XXX The new version of nsIComponentManager (once completed)
  396.     //     will obviate the need to QI to nsIComponentManagerObsolete.
  397.     //     See <http://bugzilla.mozilla.org/show_bug.cgi?id=115853>.
  398.     aCompMgr = aCompMgr.QueryInterface(
  399.                  Components.interfaces.nsIComponentManagerObsolete);
  400.     aCompMgr.registerComponentWithType(this.mClassID, this.mClassName,
  401.       this.mContractID, aFileSpec, aLocation, true, true, aType);
  402.  
  403.     // receive startup notification from the profile manager
  404.     // (we get |createInstance()|d at startup-notification time)
  405.     this.getCategoryManager().addCategoryEntry("profile-startup-category", 
  406.       this.mContractID, "", true, true);
  407.   },
  408.  
  409.   unregisterSelf: function(aCompMgr, aFileSpec, aLocation)
  410.   {
  411.     // XXX The new version of nsIComponentManager (once completed)
  412.     //     will obviate the need to QI to nsIComponentManagerObsolete.
  413.     //     See <http://bugzilla.mozilla.org/show_bug.cgi?id=115853>.
  414.     aCompMgr = aCompMgr.QueryInterface(
  415.                  Components.interfaces.nsIComponentManagerObsolete);
  416.     aCompMgr.unregisterComponentSpec(this.mClassID, aFileSpec);
  417.  
  418.     this.getCategoryManager().deleteCategoryEntry("profile-startup-category", 
  419.       this.mContractID, true);
  420.   },
  421.  
  422.   canUnload: function(aCompMgr)
  423.   {
  424.     return true;
  425.   },
  426.  
  427.   getCategoryManager: function()
  428.   {
  429.     return Components.classes["@mozilla.org/categorymanager;1"].
  430.       getService(Components.interfaces.nsICategoryManager);
  431.   },
  432.  
  433.   //////////////////////////////////////////////////////////////////////
  434.   //
  435.   //   mFactory : nsIFactory
  436.   //
  437.   //////////////////////////////////////////////////////////////////////
  438.   mFactory:
  439.   {
  440.     createInstance: function(aOuter, aIID)
  441.     {
  442.       if (aOuter != null)
  443.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  444.       if (!aIID.equals(Components.interfaces.nsIObserver) &&
  445.           !aIID.equals(Components.interfaces.nsIProfileStartupListener) &&
  446.           !aIID.equals(Components.interfaces.nsISupports))
  447.         throw Components.results.NS_ERROR_INVALID_ARG;
  448.  
  449.       // return the singleton 
  450.       return nsUpdateNotifier.QueryInterface(aIID);
  451.     },
  452.  
  453.     lockFactory: function(aLock)
  454.     {
  455.       // quiten warnings
  456.     }
  457.   }
  458. };
  459.  
  460. function NSGetModule(aCompMgr, aFileSpec)
  461. {
  462.   return nsUpdateNotifierModule;
  463. }
  464.  
  465. ////////////////////////////////////////////////////////////////////////
  466. //
  467. //   Debug helper
  468. //
  469. ////////////////////////////////////////////////////////////////////////
  470. if (!kDebug)
  471.   debug = function(m) {};
  472. else
  473.   debug = function(m) {dump("\t *** nsUpdateNotifier: " + m + "\n");};
  474.